package com.sf.service.impl;

import com.sf.domain.Amount;
import com.sf.domain.Employee;
import com.sf.domain.Order;
import com.sf.domain.Product;
import com.sf.mapper.OrderMapper;
import com.sf.qo.QueryObject;
import com.sf.service.IAmountService;
import com.sf.service.IOrderService;
import com.sf.service.IProductService;
import com.sf.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private IProductService productService;

    @Autowired
    private IAmountService amountService;



    @Override
    public PageResult query(QueryObject queryObject) {
        // 如何去判断数据库当中是否有数据
        // 1 查询数据库当中总条数, 如果为0 表述数据库中没有数据
        Integer count = orderMapper.selectForCount();
        if(count == 0 ){
            return new PageResult(queryObject.getCurrentPage(),
                    queryObject.getPageSize(),
                    Collections.emptyList(),
                    0);
        }
        // 2 如果有数据进行分页
        List<Order> list =  orderMapper.selectForList(queryObject);
        return new PageResult(queryObject.getCurrentPage(),queryObject.getPageSize(),list,count);
    }

    @Override
    @Transactional
    public void buy(Long productId, HttpSession session) {
        // 根据商品id 把商品信息查询出来
        Product product = productService.get(productId);

        // 从session 当中获取用户信息 Employee
        Employee employee = (Employee) session.getAttribute("USER_IN_SESSION");
        // 根据employee.getId(), 查询amount 账户表
        Long id = employee.getId();
        // 判断商品账户余额和购买商品价格
        Amount amount = amountService.getAmountByUserId(id);

        if(amount.getAmount().intValue() < product.getPrice().intValue()){
            throw new RuntimeException("账户余额不足");
        }
        // 判断商品库存是否足够
        if(product.getStock()<=0){
            throw new RuntimeException("商品库存不足");
        }

        // 减少库存    product    减少账户余额  userId  amount
        productService.updateStock(product.getId());
        // 减少账户余额   amount
        amountService.updateAmount(id,product.getPrice());
        // 创建订单对象, 把商品信息,其他信息设置到订单中
        Order order = new Order();
        order.setCreateTime(new Date());
        order.setOrderNo(UUID.randomUUID().toString());
        order.setProductId(productId);
        order.setProductName(product.getProductName());
        order.setStock(1);
        // 把订单信息保存到数据库中 order 表
        orderMapper.save(order);
    }

}
